import json

from client import es_client
from utils.logger_util import logger
from client.redis_client import r
from utils.date_utils import timestamp_to_str_000z


async def save_out_record(imei: str, out_timestamp, in_timestamp):
    source = json.loads(r.hget('state_' + imei, 'source'))
    data = {
        "dataAuthority": source['dataAuthority'],
        "inTime": timestamp_to_str_000z(in_timestamp),
        "intervals": (int(in_timestamp)-int(out_timestamp))*1000,
        "nickName": source['name'],
        "imei": imei,
        "outTime": timestamp_to_str_000z(int(out_timestamp))
    }
    es = await es_client.get_es_client()
    await es.index_document(index='p_out_and_in_fence_record', doc=data)
    r.hdel('out', imei)
    logger.info(f'p_out_and_in_fence_record存入记录{data}，并清除出围栏记录imei{imei}')
